﻿################### Configurable items ###################

#The path to the App.settings for UL360SurveyService, path is relative to the script file, MUST HAVE TRAILING BACKSLASH, example: "subfolder\subfolder\"
$exeConfigPath = "\"

#Number of attempts to revive service before mailing
$numberOfAttempts = 1

#Time (h) to wait before making new attempts to revive service and mailing about error
$timeToWait = 24

################### Configurable items ###################

#Name of service
$serviceName = "UL360SurveyService"

#Scriptpath
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

#Get appsettings
[xml]$appSettings = Get-Content "$($scriptPath)\$($exeConfigPath)UL360SurveyService.exe.config"

#SMTP Settings
$SMTPHost = ($appSettings.configuration.appSettings.add | Where-Object Key -eq "SMTPHost").value
$SMTPPort = ($appSettings.configuration.appSettings.add | Where-Object Key -eq "SMTPPort").value
$SMTPUser = ($appSettings.configuration.appSettings.add | Where-Object Key -eq "SMTPUser").value
$SMTPPassword = ($appSettings.configuration.appSettings.add | Where-Object Key -eq "SMTPPassword").value
$sender = ($appSettings.configuration.appSettings.add | Where-Object Key -eq "FromAddress").value

#Get creds if supplied
if($SMTPUser -ne "" -or $SMTPPassword -ne "")
{
    $secpasswd = ConvertTo-SecureString $SMTPPassword -AsPlainText -Force
    $SMTPCreds = New-Object System.Management.Automation.PSCredential ($SMTPUser, $secpasswd)
}
else
{
    $SMTPCreds = ""
}

#Error reports receiver
$ErrorReportsReceiver = ($appSettings.configuration.appSettings.add | Where-Object Key -eq "ErrorReportsReceiver").value

#File path of file containing latest status
$latestStatusFilePath = "$($scriptPath)\latest_status.txt"

#If latest status file could be found
if(Test-Path $latestStatusFilePath)
{
    $latestRun = Import-Csv $latestStatusFilePath -Encoding UTF8 -Delimiter "|"
    $latestRun.lastAttemptStarting = Get-Date $latestRun.lastAttemptStarting
}
else
{
    #Default settings for last run
    $latestRun = New-Object PSObject
    $latestRun | Add-Member NoteProperty -Name status -Value "Running"
    $latestRun | Add-Member NoteProperty -Name lastAttemptStarting -Value (Get-Date).AddHours(-$timeToWait + 1)
}

#Number of attempts done to revive service
$attemptsDone = 0

#Status of service
$status = "Running"

#Check service status
do
{
    #Get status of service
    $status = (Get-Service $serviceName).status
    
    #Next time to attempt starting service
    $nextAttempt = $latestRun.lastAttemptStarting.AddHours($timeToWait)

    #If service is stopped or paused and timetowait has passed if service was stopped or paused earlier
    if( ($status -eq "Stopped" -or $status -eq "Paused") -and ( ($latestRun.status -eq "Stopped" -or $latestRun.status -eq "Paused" -and (Get-Date) -gt $nextAttempt) -or ($latestRun.status -eq "Running") ) )
    {
        #Start service
        Set-Service $serviceName -Status Running
        
        #Get status again
        $status = (Get-Service $serviceName).status
        
        #Increment number of attempts
        $attemptsDone++
    }
}
while(($status -eq "Stopped" -or $status -eq "Paused") -and $attemptsDone -lt $numberOfAttempts -and ( ($latestRun.status -eq "Stopped" -or $latestRun.status -eq "Paused" -and (Get-Date) -gt $nextAttempt) -or ($latestRun.status -eq "Running") ))

#If the service is not running and the number of attempts to revive the service is the same as the number of attempts done, then send mail
if( ($status -eq "Stopped" -or $status -eq "Paused") -and $numberOfAttempts -eq $attemptsDone)
{
    Mail-ErrorReport `            -SMTPHost $SMTPHost `            -SMTPPort $SMTPPort `            -SMTPCreds $SMTPCreds `            -sender $sender `            -numberOfAttempts $numberOfAttempts `            -timeToWait $timeToWait `            -receiver $ErrorReportsReceiver
    $latestRun.lastAttemptStarting = Get-Date
}

#Set latestRunStatus to current status
$latestRun.status = $status
$latestRun | Export-Csv -Path $latestStatusFilePath -Delimiter "|" -Encoding UTF8 -NoTypeInformation

#Function to send mail
Function Mail-ErrorReport ($SMTPHost, $SMTPPort, $SMTPCreds, $numberOfAttempts, $timeToWait, $sender, $receiver)
{
    $subject = "Tjänsten för e-postutskick av deltagarenkäter för kurser har stannat"
    
    $message = "Tjänsten för e-postutskick av deltagarenkäter för kurser har stannat och alla försök att återuppta den har misslyckats.
    $($numberOfAttempts) st försök kommer att göras igen om $($timeToWait) timmar, misslyckas dessa 
    så kommer ytterligare ett e-post med denna felrapport att skickas ut. Ytterligare felsökning kan krävas för att hitta orsaken till felet."
    
    #Send with creds
    if($SMTPCreds -ne "")
    {
        Send-MailMessage `            -To $receiver `            -SmtpServer $SMTPHost `            -Port $SMTPPort `            -Credential $SMTPCreds `            -Subject $subject `            -BodyAsHtml $message `            -From $sender `
            -Encoding Unicode
    }
    #Send without creds
    else
    {
        Send-MailMessage `            -To $receiver `            -SmtpServer $SMTPHost `            -Port $SMTPPort `            -Subject $subject `            -BodyAsHtml $message `            -From $sender `
            -Encoding Unicode
    }
}